<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { OPERATION_TYPE } from '@/api/type.ts'
import type { Role } from '@/api/acl/role/type.ts'
import { reqRoleAddOrUpdate } from '@/api/acl/role'
import { ElMessage, FormRules } from 'element-plus'

const props = defineProps<{
  operate?: OPERATION_TYPE
}>()

const $emit = defineEmits(['get-role-list'])

const show = ref<boolean>(false)

const roleParams = reactive<Role>({
  id: '',
  roleName: '',
})
const formRef = ref<any>()

const rules: FormRules<Role> = {
  roleName: [{ required: true, message: '角色名不能为空', trigger: 'blur' }],
}

const onConfirm = async () => {
  try {
    await formRef.value?.validate()

    const { code, message } = await reqRoleAddOrUpdate(roleParams)
    if (code == 200) {
      ElMessage.success(operateName.value + '成功')
      if (props?.operate == OPERATION_TYPE.ADD) {
        $emit('get-role-list')
      } else {
        $emit('get-role-list', 1)
      }
      show.value = false
    } else {
      ElMessage.error(message)
    }
  } catch (e: any) {
    e?.message && ElMessage.error(e.message)
  }
}

const onCancel = () => {
  show.value = false
}

const initRole = (role: Role | null = null) => {
  formRef.value?.clearValidate()
  resetRole()
  if (role?.id) {
    Object.assign(roleParams, role)
  }
  show.value = true
}

const resetRole = () => {
  Object.assign(roleParams, {
    id: '',
    roleName: '',
  })
}

const operateName = computed(() => {
  return props.operate == OPERATION_TYPE.ADD ? '添加' : '修改'
})

defineExpose({
  initRole,
})
</script>

<template>
  <el-dialog v-model="show">
    <template #header>
      <h4>{{ operateName }}角色</h4>
    </template>
    <template #default>
      <el-form :model="roleParams" :rules="rules" ref="formRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleParams.roleName"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="onConfirm">确认</el-button>
      <el-button @click="onCancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
